#!/usr/bin/env python
# -*- coding: utf-8 -*-
from datetime import datetime


class state_def:
    REQUESTED, RESCHEDULED, RESOURCED, DRAFTED, CANCELED = range(1,6)


def build_row_dict(cd, row):
    d = {}
    for i, c in enumerate(row):
        if cd[i][1] == datetime:
            row[i] = row[i].strftime('%Y-%m-%d %H:%M:%S') if row[i] else None
        elif cd[i][1] == str:
            row[i] = sql_unstring(row[i]) if (row[i] or (row[i] == '')) else None
        d[cd[i][0]] = row[i]
    return d


def build_empty_row_dict(cd):
    d = {}
    for i, c in enumerate(cd):
        d[cd[i][0]] = None
    return d


def fill_dict_from_form(d, cd, form):
    for i, c in enumerate(cd):
        name = cd[i][0]
        if form.has_key(name):
            v = form[name]
            type = cd[i][1]
            encoder = type_map_form.get(type, type)
            v = encoder(v)
            d[name] = v
    return d


def build_row_dict_for_sql(cd, row):
    d = {}
    for i, c in enumerate(row):
        name = cd[i][0]
        if row[i] == None:
            v = None
        else:
            v = row[i]
            type = cd[i][1]
            encoder = type_map.get(type, type)
            v = encoder(v)      
        d[name] = v
    return d


def build_columns_values_sql(d):
    for k, v in d.iteritems():
        if v == None:
            d[k] = 'NULL'
    columns_string = ' (' + ', '.join(str(k) for k, v in d.iteritems()) + ')'
    values_string = ' (' + ', '.join(str(v) for k, v in d.iteritems()) + ')'
    return columns_string + ' VALUES' + values_string


def sql_string(v):
    v = v.replace("'", "''")
    v = v.replace("\\", "\\\\")
    v = v.replace(";", "\;")
    return "'%s'" % v


def sql_int(v):
    v = int(v)
    return "%s" % v


def sql_date(v):
    v = v.strftime('%Y-%m-%d %H:%M:%S')
    return "'%s'" % v


def sql_bool(v):
    if v == True:
        return '1'
    return '0'


def sql_unstring(v):
    v = v.replace("\;", ";")
    v = v.replace("\\\\", "\\")
    v = v.replace("''", "'")
    return v


type_map = {
    str: sql_string,
    int: sql_int,
    datetime: sql_date,
    bool: sql_bool,
    }


type_map_form = {
    str: sql_string,
    int: sql_int,
    datetime: sql_string,
    bool: sql_int,
    }